package com.pega.eprescription.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;

import com.pega.eprescription.EditPillListAdapter;
import com.pega.eprescription.R;
import com.pega.eprescription.alarm.AlarmReceiver;
import com.pega.eprescription.database.manager.DatabaseManager;
import com.pega.eprescription.database.model.Pill;
import com.pega.eprescription.database.model.Prescription;
import com.pega.eprescription.pref.Prefs;

public class EditPrescription extends Activity {
	boolean isEditing = false;
	private ListView listView;
	private TextView prescriptionName;
	private TextView prescriptionDay;
	private Prescription currentPrescription;
	private MenuItem item_edit;
	private MenuItem item_calendar;
	private MenuItem item_done;
	// private MenuItem item_cancel;
	private Button addmoreBtn;
	private TextView mo;
	private TextView no;
	private TextView ev;
	private TextView items;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit_prescription);

		getWindow().setSoftInputMode(
			      WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		
		int id = getIntent().getIntExtra("PreID", -1);

		
		
		if (id != -1) {// not start from main activity
			currentPrescription = DatabaseManager
					.getInstance(getApplicationContext())
					.getAllPrescriptionRecord().get(id);

		} else {
			currentPrescription = DatabaseManager.getInstance(
					getApplicationContext()).getCurrentPrescription();

		}
		if (currentPrescription == null) {
			// back to
			finish();
		} else {
			ArrayList<Pill> pills = DatabaseManager.getInstance(
					getApplicationContext()).getAllPillOfPrescription(
					currentPrescription);
			items = (TextView)findViewById(R.id.items);
			items.setText(""+pills.size()+" Items(s)");
			prescriptionName = (TextView) findViewById(R.id.tenbenh);
			prescriptionName.setText(currentPrescription.getNamePre());

			prescriptionDay = (TextView) findViewById(R.id.ngaybenh);
			prescriptionDay.setText(new SimpleDateFormat("dd-MM-yyyy")
					.format(currentPrescription.getStartDate()));

			prescriptionDay.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Calendar cal = Calendar.getInstance();

					cal.setTime(currentPrescription.getStartDate());
					int year = cal.get(Calendar.YEAR);
					int month = cal.get(Calendar.MONTH);
					int day = cal.get(Calendar.DAY_OF_MONTH);
					new DatePickerDialog(EditPrescription.this,
							new OnDateSetListener() {

								@Override
								public void onDateSet(DatePicker view,
										int year, int monthOfYear,
										int dayOfMonth) {
									Calendar a = Calendar.getInstance();
									a.set(year, monthOfYear, dayOfMonth);

									currentPrescription.setStartDate(a
											.getTime());
									prescriptionDay
											.setText(new SimpleDateFormat(
													"dd-MM-yyyy")
													.format(currentPrescription
															.getStartDate()));

								}
							}, year, month, day).show();
				}
			});

			mo = (TextView) findViewById(R.id.morningtv);
			no = (TextView) findViewById(R.id.noontv);
			ev = (TextView) findViewById(R.id.eveningtv);

			mo.setText(currentPrescription.getMorningTime());
			mo.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					String motime = currentPrescription.getMorningTime();
					String[] a = motime.split(":");
					int hour = Integer.parseInt(a[0]);
					int minute = Integer.parseInt(a[1]);
					new TimePickerDialog(EditPrescription.this,
							new OnTimeSetListener() {

								@Override
								public void onTimeSet(TimePicker arg0,
										int arg1, int arg2) {
									currentPrescription.setMorningTime(arg1
											+ ":" + arg2);
									mo.setText(currentPrescription
											.getMorningTime());

								}
							}, hour, minute, true).show();
					;

				}
			});

			no.setText(currentPrescription.getNoonTime());
			no.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					String motime = currentPrescription.getNoonTime();
					String[] a = motime.split(":");
					int hour = Integer.parseInt(a[0]);
					int minute = Integer.parseInt(a[1]);
					new TimePickerDialog(EditPrescription.this,
							new OnTimeSetListener() {

								@Override
								public void onTimeSet(TimePicker arg0,
										int arg1, int arg2) {
									currentPrescription.setNoonTime(arg1 + ":"
											+ arg2);
									no.setText(currentPrescription
											.getNoonTime());

								}
							}, hour, minute, true).show();
					;

				}
			});

			ev.setText(currentPrescription.getEverningTime());
			ev.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					String motime = currentPrescription.getEverningTime();
					String[] a = motime.split(":");
					int hour = Integer.parseInt(a[0]);
					int minute = Integer.parseInt(a[1]);
					new TimePickerDialog(EditPrescription.this,
							new OnTimeSetListener() {

								@Override
								public void onTimeSet(TimePicker arg0,
										int arg1, int arg2) {
									currentPrescription.setEverningTime(arg1
											+ ":" + arg2);
									ev.setText(currentPrescription
											.getEverningTime());

								}
							}, hour, minute, true).show();
					;

				}
			});

			final ArrayList<Pill> allPill = DatabaseManager.getInstance(
					getApplicationContext()).getAllPillOfPrescription(
					currentPrescription);
			EditPillListAdapter adapter = new EditPillListAdapter(this,
					allPill, false);
			listView = (ListView) findViewById(R.id.listview);
			listView.setAdapter(adapter);

		}
		addmoreBtn = (Button) findViewById(R.id.add_btn);
		addmoreBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(EditPrescription.this, EditDrug.class);	
				intent.putExtra("ID_PRESCRIPT_PASS", currentPrescription.getPrescripId());
				EditPrescription.this.startActivity(intent);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.edit_precsription, menu);
		item_edit = menu.findItem(R.id.edit_prescreption_edit);
		item_calendar = menu.findItem(R.id.edit_prescreption_calendar);
		item_done = menu.findItem(R.id.edit_prescreption_done);
		// item_cancel = menu.findItem(R.id.edit_prescreption_cancel);

		item_edit.setVisible(true);
		item_calendar.setVisible(true);
		item_done.setVisible(false);
		// item_cancel.setVisible(false);
		addmoreBtn.setVisibility(View.GONE);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.edit_prescreption_edit:
			isEditing = true;
			item_edit.setVisible(false);
			item_calendar.setVisible(false);
			item_done.setVisible(true);
			
			// item_cancel.setVisible(true);
			break;
		case R.id.edit_prescreption_calendar:
			startActivity(new Intent(this, DailyRemindActivity.class));
			break;

		case R.id.edit_prescreption_done:
			isEditing = false;
			item_edit.setVisible(true);
			item_calendar.setVisible(true);
			item_done.setVisible(false);
			// item_cancel.setVisible(false);
			DatabaseManager.getInstance(this).updatePrescriptionRecord(
					currentPrescription);
			
			Prefs.sharedInstance(this).updateMorningAlarm(
					currentPrescription.getMorningTime());
			Prefs.sharedInstance(this).updateAfternoonAlarm(
					currentPrescription.getNoonTime());
			Prefs.sharedInstance(this).updateEveningAlarm(
					currentPrescription.getEverningTime());
			new AlarmReceiver().setAlarm(this);
			break;

		
		  case R.id.setting: 
			  startActivity(new Intent(this, SettingActivity.class));
			  break;
		 

		default:
			break;
		}
		final ArrayList<Pill> allPill = DatabaseManager.getInstance(
				getApplicationContext()).getAllPillOfPrescription(
				currentPrescription);

		if (isEditing) {
			prescriptionName.setEnabled(true);
			prescriptionDay.setEnabled(true);
			mo.setEnabled(true);
			no.setEnabled(true);
			ev.setEnabled(true);
			EditPillListAdapter adapter = new EditPillListAdapter(
					this, allPill, true);
			listView.setAdapter(adapter);

			addmoreBtn.setVisibility(View.VISIBLE);
		} else {

			addmoreBtn.setVisibility(View.GONE);
			prescriptionName.setEnabled(false);
			prescriptionDay.setEnabled(false);
			mo.setEnabled(false);
			no.setEnabled(false);
			ev.setEnabled(false);
			EditPillListAdapter adapter = new EditPillListAdapter(
					this, allPill, false);
			listView.setAdapter(adapter);
		}

		listView.invalidateViews();
		return false;
	}

}
